import { AppMenuController } from '@ibiz-template/runtime';
import { useNamespace } from '@ibiz-template/vue3-util';
import { defineComponent, getCurrentInstance, PropType, ref } from 'vue';
import { showTitle } from '@ibiz-template/core';
import { CustomThemeController } from './custom-theme.controller';
import './custom-theme.scss';

export const CustomTheme = defineComponent({
  name: 'IBizCustomTheme',
  props: {
    controller: {
      type: Object as PropType<AppMenuController>,
      required: true,
    },
  },
  emits: [],
  setup() {
    const ns = useNamespace(`custom-theme`);

    const vue = getCurrentInstance()!.proxy!;

    const c = new CustomThemeController();

    const activeTab = ref(0);

    const handleThemeChange = (codeName: string) => {
      c.state.themeTag = codeName;
    };

    const handleColorChange = (
      varName: string,
      color: string,
      className?: string,
    ) => {
      let name = varName;
      if (className) {
        name = `${className}:${varName}`;
      }
      c.state.themeVars[name] = color;
    };

    const handleSizeChange = (varName: string, size: number, item: IData) => {
      c.calcSizeChange(varName, size, item);
    };

    const handlePreview = () => {
      ibiz.util.theme.previewCustomTheme(c.state.themeTag, c.state.themeVars);
      vue.$forceUpdate();
    };

    const handleSave = async () => {
      ibiz.util.theme.previewCustomTheme(c.state.themeTag, c.state.themeVars);
      vue.$forceUpdate();
      await ibiz.util.theme.saveCustomTheme(
        c.state.themeTag,
        c.state.themeVars,
      );
    };

    const handleReset = () => {
      c.state.themeVars = {};
      ibiz.util.theme.resetCustomTheme();
      vue.$forceUpdate();
    };

    const handleShare = async () => {
      ibiz.util.theme.previewCustomTheme(c.state.themeTag, c.state.themeVars);
      vue.$forceUpdate();
      await ibiz.util.theme.saveCustomTheme(
        c.state.themeTag,
        c.state.themeVars,
      );
      const shareUrl = await ibiz.util.theme.shareCustomTheme(
        c.state.themeTag,
        c.state.themeVars,
      );
      if (shareUrl) {
        const confirm = await ibiz.confirm.info({
          title: ibiz.i18n.t('control.common.customTheme.confirmCopyLink'),
          desc: `${shareUrl}`,
        });
        if (confirm) {
          ibiz.util.text.copy(shareUrl);
        }
      }
    };

    const renderColorPicker = (data: IData) => {
      let { value } = data;
      if (data.className) {
        value = `${data.className}:${value}`;
      }
      return (
        <el-color-picker
          onChange={(val: string) => {
            handleColorChange(data.value, val, data.className);
          }}
          show-alpha
          model-value={c.getCssVar(value, data.defaultValue)}
        />
      );
    };

    const renderSizeInput = (data: IData) => {
      const varValue = c.getCssVar(data.value) as number;
      return (
        <el-input-number
          model-value={varValue}
          step={varValue >= 100 ? 100 : 1}
          min={0}
          onChange={(value: number) => {
            handleSizeChange(data.value, value, data);
          }}
        />
      );
    };

    const renderItem = (item: IData) => {
      if (item.children) {
        return item.children.map((children: IData) => {
          return renderItem(children);
        });
      }
      return (
        <div class={ns.b('item')}>
          <div class={ns.be('item', 'caption')}>
            {ibiz.i18n.t(`control.common.customTheme.${item.labelLang}`)}
          </div>
          <div class={ns.be('item', 'content')}>
            {item.vars.map((data: IData) => {
              let content = renderColorPicker(data);
              if (data.type === 'size') {
                content = renderSizeInput(data);
              }
              return (
                <div class={ns.b('var')}>
                  <span
                    class={ns.be('var', 'description')}
                    title={showTitle(
                      ibiz.i18n.t(
                        `control.common.customTheme.${data.descLang}`,
                      ),
                    )}
                  >
                    {ibiz.i18n.t(
                      `control.common.customTheme.${data.labelLang}`,
                    )}
                  </span>
                  {content}
                </div>
              );
            })}
          </div>
        </div>
      );
    };

    const renderHeader = () => {
      return (
        <div class={ns.b('item')}>
          <div class={ns.be('item', 'caption')}>
            {ibiz.i18n.t('control.common.customTheme.themeColor')}
          </div>
          <div class={ns.be('item', 'content')}>
            {c.predefineType.map((item: IData) => {
              return (
                <el-button
                  color={item.color}
                  title={showTitle(
                    ibiz.i18n.t(`control.common.customTheme.${item.labelLang}`),
                  )}
                  onClick={() => {
                    handleThemeChange(item.codeName);
                  }}
                >
                  {c.state.themeTag === item.codeName && (
                    <ion-icon name='checkmark-sharp'></ion-icon>
                  )}
                </el-button>
              );
            })}
          </div>
        </div>
      );
    };

    const renderContent = () => {
      return (
        <el-tabs v-model={activeTab.value}>
          {c.model.map((item: IData, index: number) => {
            return (
              <el-tab-pane
                name={index}
                label={ibiz.i18n.t(
                  `control.common.customTheme.${item.labelLang}`,
                )}
              >
                {renderItem(item)}
              </el-tab-pane>
            );
          })}
        </el-tabs>
      );
    };

    return {
      ns,
      c,
      handlePreview,
      handleReset,
      handleSave,
      handleShare,
      renderHeader,
      renderContent,
    };
  },

  render() {
    return (
      <div class={this.ns.b()}>
        <div class={this.ns.b('header')}>{this.renderHeader()}</div>
        <div class={this.ns.b('content')}>{this.renderContent()}</div>
        <div class={this.ns.b('footer')}>
          <el-button onClick={this.handlePreview}>
            {ibiz.i18n.t('control.common.customTheme.preview')}
          </el-button>
          <el-button onClick={this.handleSave}>
            {ibiz.i18n.t('control.common.customTheme.save')}
          </el-button>
          <el-button onClick={this.handleReset}>
            {ibiz.i18n.t('control.common.customTheme.reset')}
          </el-button>
          {/* <el-button onClick={this.handleShare}>
            {ibiz.i18n.t('control.common.customTheme.share')}
          </el-button> */}
        </div>
      </div>
    );
  },
});
